import { Injectable } from '@nestjs/common';
import {
  Order_Find_Dto,
  Order_Cancel_Dto,
  Order_Pay_Dto,
  Order_Refund_Dto,
  Order_Update_Dto,
  Order_Create_Dto,
} from './assets/order.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Order } from './assets/order.entity';
import { EntityManager, Repository } from 'typeorm';
import { util_Db_PageList } from '@/common/util/db';
import {
  Constant_Enum_Enum_Scheduled_Type,
  Constant_Enum_Enum_Order_PayType,
  Constant_Enum_Enum_Order_PayStatus,
  Constant_Enum_Enum_Scheduled_Status,
  Constant_Enum_Enum_Coupon_Type,
  Constant_Enum_Enum_CouponUserClient_Status,
  Constant_Enum_Enum_Rebates_RebatesType,
  Constant_Enum_Enum_UserClient_Type,
  Constant_Enum_Enum_Rebates_DistributionStatus,
} from '@/common/constants/enum';
import { Product_Service } from '../product/product.service';
import { UserClient } from '../userClient/assets/userClient.entity';
import { Seat_Service } from '../seat/seat.service';
import { Seat } from '../seat/assets/seat.entity';
import { Alipay_Service } from '../../commonModule/alipay/alipay.service';
import { SchedulerRegistry, Timeout } from '@nestjs/schedule';
import { Scheduled } from '../../commonModule/scheduled/assets/scheduled.entity';
import { Scheduled_Service } from '../../commonModule/scheduled/scheduled.service';
import { Class_HttpException_Base } from '@/common/classes/httpException';
import { Good } from '../good/assets/good.entity';
import { util_Index_RandomString } from '@/common/util/index';
import { Alipay_PayCallBack_SeClass } from '../../commonModule/alipay/assets/alipay.class';
import { Coupon } from '../coupon/assets/coupon.entity';
import { IRequest } from '@/common/typeScripts';
import {
  util_Decimal_Divide,
  util_Decimal_Multiply,
  util_Decimal_Subtract,
} from '@/common/util/decimaled';
import { CouponUserClient } from '../couponUserClient/assets/couponUserClient.entity';
import { Rebates } from '../rebates/assets/rebates.entity';
import { DistributionRate } from '../distributionRate/assets/distributionRate.entity';
import { OrderVirtualDetail } from '../orderVirtualDetail/assets/orderVirtualDetail.entity';

@Injectable()
export class Order_Service {
  constructor(
    @InjectRepository(CouponUserClient)
    private couponUserClient_Repository: Repository<CouponUserClient>,
    @InjectRepository(UserClient)
    private userClient_Repository: Repository<UserClient>,
    @InjectRepository(Order)
    private order_Repository: Repository<Order>,
    @InjectRepository(Good)
    private good_Repository: Repository<Good>,
    @InjectRepository(Seat)
    private seat_Repository: Repository<Seat>,
    @InjectRepository(Rebates)
    private rebates_Repository: Repository<Rebates>,
    @InjectRepository(Coupon)
    private coupon_Repository: Repository<Coupon>,
    @InjectRepository(DistributionRate)
    private distributionRate_Repository: Repository<DistributionRate>,
    private product_Service: Product_Service,
    private alipay_Service: Alipay_Service,
    private scheduled_Service: Scheduled_Service,
    private entityManager: EntityManager,
    private schedulerRegistry: SchedulerRegistry,
  ) {}

  async order_Create(body: Order_Create_Dto, req: IRequest) {
    return await this.entityManager.transaction(async (manage) => {
      // 1.如有未支付订单先取消未支付订单
      const resdd = await this.order_Repository
        .createQueryBuilder('order')
        .andWhere(`order.userClientId = :userClientId`, { userClientId: req.user.userId })
        .andWhere(`order.status = :status`, {
          status: Constant_Enum_Enum_Order_PayStatus.order_PayStatus_ToPay,
        })
        .getOne();
      if (resdd) throw new Class_HttpException_Base('请先取消未支付订单');

      //2.添加或者修改商品
      const productRecord = await this.product_Service.productFindOneById(body.productId);
      const userClient = this.userClient_Repository.create({
        id: req.user.userId,
      });
      let good = await this.good_Repository
        .createQueryBuilder('good')
        .leftJoinAndSelect('good.product', 'product')
        .where(`good.productId = :id`, { id: body.productId })
        .andWhere('good.seatsNum <= :seatsNum', {
          seatsNum: productRecord.productNum,
        })
        .getOne();
      if (good) {
        good.seatsNum = good.seatsNum + 1;
      } else {
        good = this.good_Repository.create({
          account: '等待分配',
          password: '00000000',
          product: productRecord,
          seatsNum: 1,
        });
      }
      good = await manage.save(good);

      // 3.添加订单
      const orderClass = this.order_Repository.create({
        payPrice: productRecord.productPrice,
        userClient: userClient,
        status: Constant_Enum_Enum_Order_PayStatus.order_PayStatus_ToPay,
        orderNumber: util_Index_RandomString({ length: 12 }),
      });
      let order = await manage.save(Order, orderClass);
      const OrderVirtualDetailed = await manage.save(OrderVirtualDetail, {
        virtualTime: productRecord.productTime,
        good: good,
        order,
      });

      // 4.添加座位
      const seat = this.seat_Repository.create({
        good: good,
        userClient: userClient,
      });
      const seated = await manage.save(seat);
      OrderVirtualDetailed.seat = seated;
      order = await manage.save(Order, orderClass);

      // 5.优惠券处理
      if (body.couponId) {
        const couponUserClient = await this.couponUserClient_Repository
          .createQueryBuilder('couponUserClient')
          .leftJoinAndSelect('couponUserClient.coupon', 'coupon')
          .where(`coupon.id = :id`, { id: body.couponId })
          .andWhere(`couponUserClient.userClient = :userClient`, { userClient: req.user.userId })
          .getOne();
        if (couponUserClient.fixedTimeEnd < new Date().getTime())
          throw new Class_HttpException_Base('优惠券已过期');
        if (couponUserClient.fixedTimeStart > new Date().getTime())
          throw new Class_HttpException_Base('优惠券待生效');
        couponUserClient.status =
          Constant_Enum_Enum_CouponUserClient_Status.CouponUserClient_Status_Using;
        await manage.update(CouponUserClient, couponUserClient.id, couponUserClient);
        order.coupon = this.coupon_Repository.create({
          id: body.couponId,
        });
        const productRecord = await this.product_Service.productFindOneById(
          OrderVirtualDetailed.good.product.id,
        );
        if (!couponUserClient.coupon) throw new Class_HttpException_Base('找不到该优惠券');
        let priceCoupon = '0';
        if (couponUserClient.coupon.couponType == Constant_Enum_Enum_Coupon_Type.Coupon_Type_Discount) {
          priceCoupon = util_Decimal_Multiply(
            productRecord.productPrice,
            Number(util_Decimal_Divide(couponUserClient.coupon.discount, 10)),
          );
        } else {
          if (productRecord.productPrice > couponUserClient.coupon.reducePrice)
            throw new Class_HttpException_Base('还未满满减价格！');
          priceCoupon = util_Decimal_Subtract(
            productRecord.productPrice,
            couponUserClient.coupon.reducePrice,
          );
        }
        order.payPrice = Number(priceCoupon);
      }

      // 6.分销处理
      if (body.distributionCode) {
        const rebates = this.rebates_Repository.create({
          order,
          invitee: this.userClient_Repository.create({ id: req.user.userId }),
        });
        // 6.1 分销单类处理
        const orderNum = await this.order_Repository
          .createQueryBuilder('order')
          .where(`order.userClientId=:userClientId`, { userClientId: req.user.userId })
          .andWhere(`order.status IN (:...status)`, {
            status: [
              Constant_Enum_Enum_Order_PayStatus.order_PayStatus_Pay,
              Constant_Enum_Enum_Order_PayStatus.order_PayStatus_Refund,
            ],
          })
          .getCount();
        rebates.rebatesType =
          orderNum == 0
            ? Constant_Enum_Enum_Rebates_RebatesType.Rebates_RebatesType_FirstOrder
            : orderNum == 1
              ? Constant_Enum_Enum_Rebates_RebatesType.Rebates_RebatesType_SecondedOrder
              : Constant_Enum_Enum_Rebates_RebatesType.Rebates_RebatesType_OtherOrder;

        // 6.2 分销金额处理
        if (orderNum < 2) {
          const userClient = await this.userClient_Repository
            .createQueryBuilder('userClient')
            .where('userClient.id=:userClientId', { userClientId: req.user.userId })
            .getOne();
          const distributionRateQb = this.distributionRate_Repository
            .createQueryBuilder('distributionRate')
            .leftJoin('distributionRate.product', 'product')
            .where(`product.id=:productId`, { productId: OrderVirtualDetailed.good.product.id });
          if (userClient.distributionType == Constant_Enum_Enum_UserClient_Type.UserClient_Type_Lock) {
            distributionRateQb.where(`distributionRate.userClientId=:userClientId`, {
              userClientId: req.user.userId,
            });
          } else {
            distributionRateQb.where('distributionRate.userClientId IS NULL');
          }
          const distributionRate = await distributionRateQb.getOne();
          rebates.rebatesMoney = Number(
            orderNum == 0
              ? util_Decimal_Multiply(order.payPrice, distributionRate.firstOrderRate)
              : util_Decimal_Multiply(order.payPrice, distributionRate.secondOrderRate),
          );
        } else {
          rebates.rebatesMoney = 0;
        }

        // 6.3 返利订单邀请人
        const inviterClient = await this.userClient_Repository
          .createQueryBuilder('userClient')
          .where('userClient.distributionCode=:distributionCode', {
            distributionCode: body.distributionCode,
          })
          .getOne();
        rebates.inviter = inviterClient;
        await manage.save(Rebates, rebates);
      }

      await manage.save(Order, orderClass);

      // 6.添加取消定时
      const schedule = await this.scheduled_Service.scheduled_Create({
        scheduledName: `${order.id}-${Constant_Enum_Enum_Scheduled_Type.Scheduled_Type_OrderPay}`,
        scheduleddType: Constant_Enum_Enum_Scheduled_Type.Scheduled_Type_OrderPay,
        scheduleddDetail: JSON.stringify({ orderId: order.id }),
      });
      this.order_CancelSchedule(order.id, schedule, 100000);

      return order;
    });
  }

  @Timeout(Constant_Enum_Enum_Scheduled_Type.Scheduled_Type_OrderPay, 10000)
  async order_StartCancelOrderSchedule() {
    const res = await this.scheduled_Service.scheduled_FindAllByType();
    res.map((item, index) => {
      if (item.status == Constant_Enum_Enum_Scheduled_Status.SCHEDULED_STATUS_DONE) return;
      const orderId = JSON.parse(item.scheduleddDetail).orderId;
      const time = new Date().getTime() - new Date(item.createTime).getTime();
      this.order_CancelSchedule(orderId, item, time > 300000 ? 1000 * index : time);
    });
    this.schedulerRegistry.deleteTimeout(Constant_Enum_Enum_Scheduled_Type.Scheduled_Type_OrderPay);
  }

  async order_CancelSchedule(orderId: number, item: Scheduled, time) {
    const timeout = setTimeout(async () => {
      return await this.entityManager.transaction(async (manage) => {
        const res = await this.order_Repository
          .createQueryBuilder('order')
          .leftJoinAndSelect('order.coupon', 'coupon')
          .leftJoinAndSelect('order.userClient', 'userClient')
          .andWhere(orderId ? '1=1' : `order.id = :id`, { id: orderId })
          .getOne();
        if (res.status == Constant_Enum_Enum_Order_PayStatus.order_PayStatus_ToPay) {
          res.status = Constant_Enum_Enum_Order_PayStatus.order_PayStatus_Cancel;
          await manage.save(Order, res);
          if (res.coupon.id) {
            const couponUserClient = await this.couponUserClient_Repository
              .createQueryBuilder('couponUserClient')
              .where(`couponUserClient.coupon = :coupon`, {
                coupon: res.coupon.id,
              })
              .andWhere(`couponUserClient.userClient = :userClient`, { userClient: res.userClient.id })
              .getOne();
            couponUserClient.status = Constant_Enum_Enum_CouponUserClient_Status.ExCode_ExCodeValue_Use;
            await manage.update(CouponUserClient, couponUserClient.id, couponUserClient);
          }
          const seat = await this.seat_Repository
            .createQueryBuilder('seat')
            .leftJoinAndSelect('seat.order', 'order')
            .leftJoinAndSelect('seat.good', 'good')
            .andWhere(`order.id = :id`, { id: orderId })
            .getOne();
          await manage.delete(Seat, seat.id);
          await manage.update(Good, seat.good.id, {
            seatsNum: seat.good.seatsNum - 1,
          });
        }
        this.schedulerRegistry.deleteTimeout(
          `${orderId}-${Constant_Enum_Enum_Scheduled_Type.Scheduled_Type_OrderPay}`,
        );
        await manage.update(Scheduled, item.id, {
          status: Constant_Enum_Enum_Scheduled_Status.SCHEDULED_STATUS_DONE,
          scheduledd_at: new Date().getTime(),
        });
      });
    }, time);
    const timeouts = this.schedulerRegistry.getTimeouts();
    if (timeouts.includes(`${orderId}-${Constant_Enum_Enum_Scheduled_Type.Scheduled_Type_OrderPay}`))
      return;
    this.schedulerRegistry.addTimeout(
      `${orderId}-${Constant_Enum_Enum_Scheduled_Type.Scheduled_Type_OrderPay}`,
      timeout,
    );
  }

  async order_Web_FindByPageWeb(query: Order_Find_Dto) {
    const qb = this.order_Repository
      .createQueryBuilder('order')
      .leftJoin('order.orderVirtualDetail', 'orderVirtualDetail')
      .leftJoin('orderVirtualDetail.good', 'good')
      .leftJoin('good.product', 'product')
      .select([
        'product.productName AS productName',
        'product.productPrice AS productPrice',
        'product.productNum  AS productNum',
        'product.productImg  AS productImg',
        'product.productTime  AS productTime',
        'order.orderNumber  AS orderNumber',
        'order.createTime  AS createTime',
        'order.status  AS status',
        'order.payPlatformTradeNo  AS payPlatformTradeNo',
        'order.payPrice  AS payPrice',
        'order.payType  AS payType',
        'order.id  AS id',
      ]);
    const res = await util_Db_PageList<Order>({
      queryBuilder: qb,
      isRaw: true,
      query: {
        size: query.size,
        page: query.page,
        'order.status': query.status,
        'order.userClientId': query.userClientId,
      },
      getQuery: true,
    });
    return res;
  }

  async order_FindByPage(query: Order_Find_Dto) {
    const { size, page } = query;
    const qb = this.order_Repository
      .createQueryBuilder('order')
      .leftJoin('order.orderVirtualDetail', 'orderVirtualDetail')
      .leftJoin('orderVirtualDetail.good', 'good')
      .leftJoin('order.userClient', 'userClient')
      .leftJoin('userClient.inviteRelation', 'inviteRelation')
      .leftJoin('good.product', 'product')
      .leftJoin('product.platform', 'platform')
      .select([
        'order.id AS id',
        'order.orderNumber AS orderNumber',
        'order.status AS status',
        'platform.platFormName AS goodPlatform',
        'product.platformId AS platformId',
        'product.productName AS productName',
        'userClient.id AS userClientId',
        'userClient.userName AS userName',
        'order.payPlatformTradeNo AS payPlatformTradeNo',
        'order.payType AS payType',
        'order.refundRemark AS refundRemark',
        'order.payPrice AS payPrice',
        'order.createTime AS createTime',
        'inviteRelation.firstOrder AS firstOrderId',
        'inviteRelation.firstDistributionMoney AS firstDistributionMoney',
        'inviteRelation.secondOrder AS secondOrder',
        'inviteRelation.secondDistributionMoney AS secondDistributionMoney',
        'inviteRelation.secondDistributionStatus AS secondDistributionStatus',
        'inviteRelation.firstDistributionStatus AS firstDistributionStatus',
      ])
      .where(query.endTime ? `order.endTime = :endTime` : '1=1', {
        endTime: query.endTime,
      })
      .andWhere(query.startTime ? `order.startTime = :startTime` : '1=1', {
        startTime: query.startTime,
      });
    return await util_Db_PageList<Order>({
      queryBuilder: qb,
      isRaw: true,
      query: {
        size,
        page,
        'order.status': query.status,
        'order.orderNumber': query.orderNumber,
        'platform.id': query.platformId,
        'product.id': query.productId,
        'order.payPlatformTradeNo': query.payPlatformTradeNo,
        'order.payType': query.payType,
      },
    });
  }

  async order_FindOneById(id: number) {
    return await this.order_Repository
      .createQueryBuilder('order')
      .andWhere(`order.id = :id`, { id: id })
      .getOne();
  }

  async order_Web_FindOneById(id: number) {
    const qb = this.order_Repository
      .createQueryBuilder('order')
      .leftJoin('order.orderVirtualDetail', 'orderVirtualDetail')
      .leftJoin('orderVirtualDetail.good', 'good')
      .leftJoin('orderVirtualDetail.product', 'product')
      .leftJoin('product.platform', 'platform')
      .select([
        'product.productImg AS productImg',
        'platform.platFormName AS platFormName',
        'order.payPrice AS payPrice',
        'product.productName AS productName',
        'product.productAtention AS productAtention',
        'product.productPrice AS productPrice',
        'order.orderNumber AS orderNumber',
        'order.id AS id',
      ]);
    return await qb.andWhere(`order.id = :id`, { id: id }).getRawOne();
  }

  async order_Update(body: Order_Update_Dto) {
    return await this.entityManager.transaction(async (manage) => {
      const order = await this.order_FindOneById(body.id);
      if (!order) throw new Class_HttpException_Base('不存在该记录');
      const newRole = this.order_Repository.merge(order, body);
      return await manage.save(Order, newRole);
    });
  }

  async orderWeb_Pay(body: Order_Pay_Dto) {
    return await this.entityManager.transaction(async (manage) => {
      const order = await this.order_Repository
        .createQueryBuilder('order')
        .leftJoinAndSelect('order.orderVirtualDetail', 'orderVirtualDetail')
        .leftJoinAndSelect('orderVirtualDetail.good', 'good')
        .leftJoinAndSelect('order.coupon', 'coupon')
        .leftJoinAndSelect('good.product', 'product')
        .andWhere(`order.id = :id`, { id: body.orderId })
        .getOne();
      if (!order) throw new Class_HttpException_Base('不存在该订单');
      order.payType = Constant_Enum_Enum_Order_PayType.Order_PayType_ZfbPay;
      await manage.save(Order, order);
      if (body.payType == Constant_Enum_Enum_Order_PayType.Order_PayType_ZfbPay) {
        const result = this.alipay_Service.alipay_CreatePay({
          outTradeNo: order.orderNumber,
          totalAmount: order.payPrice,
          subject: order.orderVirtualDetail.good.product.productName,
          passback_params: String(order.id),
        });
        return result;
      } else {
        new Class_HttpException_Base('参数错误');
      }
    });
  }

  async order_Cancel(body: Order_Cancel_Dto, req: IRequest) {
    return await this.entityManager.transaction(async (manage) => {
      // 订单前置处理
      const order = await this.order_Repository
        .createQueryBuilder('order')
        .leftJoinAndSelect('order.coupon', 'coupon')
        .andWhere(`order.id = :id`, { id: body.id })
        .getOne();
      if (!order) {
        throw new Class_HttpException_Base('没有发现该订单');
      }
      if (order.status === Constant_Enum_Enum_Order_PayStatus.order_PayStatus_Cancel) {
        throw new Class_HttpException_Base('订单已取消');
      }

      // 更新商品
      const orderdd = await this.order_Repository
        .createQueryBuilder('order')
        .leftJoinAndSelect('order.orderVirtualDetail', 'orderVirtualDetail')
        .leftJoinAndSelect('orderVirtualDetail.good', 'good')
        .leftJoinAndSelect('orderVirtualDetail.seat', 'seat')
        .andWhere(`order.id = :id`, { id: body.id })
        .getOne();
      await manage.update(Good, orderdd.orderVirtualDetail.good.id, {
        seatsNum: orderdd.orderVirtualDetail.good.seatsNum - 1,
      });

      // 更新座位
      await manage.delete(Seat, orderdd.orderVirtualDetail.seat.id);

      // 更新优惠券
      if (order.coupon?.id) {
        const couponUserClient = await this.couponUserClient_Repository
          .createQueryBuilder('couponUserClient')
          .where(`couponUserClient.coupon = :coupon`, { coupon: order.coupon.id })
          .andWhere(`couponUserClient.userClient = :userClient`, { userClient: req.user.userId })
          .getOne();
        couponUserClient.status = Constant_Enum_Enum_CouponUserClient_Status.ExCode_ExCodeValue_Use;
        await manage.update(CouponUserClient, couponUserClient.id, couponUserClient);
      }

      // 更新订单状态
      await manage.update(Order, order.id, {
        status: Constant_Enum_Enum_Order_PayStatus.order_PayStatus_Cancel,
      });

      return '取消成功';
    });
  }

  async order_Refund(body: Order_Refund_Dto): Promise<string> {
    return await this.entityManager.transaction(async (manage) => {
      // 1.退款前置处理
      const order = await this.order_Repository
        .createQueryBuilder('order')
        .leftJoin('order.orderVirtualDetail', 'orderVirtualDetail')
        .andWhere(`order.id = :id`, { id: body.orderId })
        .getOne();
      if (!order) {
        throw new Error('没有发现该订单');
      }
      if (order.status === Constant_Enum_Enum_Order_PayStatus.order_PayStatus_Refund) {
        throw new Error('订单已退款');
      }

      // 退款金额限制
      const usedTime = Math.floor(Number(util_Decimal_Subtract(new Date().getTime(), order.createTime)));
      const allTime = order.orderVirtualDetail.virtualTime;
      const maxRefundPrice = util_Decimal_Multiply(
        Number(util_Decimal_Divide(allTime, usedTime)),
        order.payPrice,
      );
      let maxRefundPricedd = maxRefundPrice;
      const rebates = await this.rebates_Repository
        .createQueryBuilder('Rebates')
        .leftJoin('Rebates.order', 'Rebaordertes')
        .where('order.id =:orderId', { orderId: order.id })
        .getOne();
      if (
        rebates &&
        (rebates.rebatesStatus ==
          Constant_Enum_Enum_Rebates_DistributionStatus.InviteRelation_DistributionStatus_Accouted ||
          rebates.rebatesStatus ==
            Constant_Enum_Enum_Rebates_DistributionStatus.InviteRelation_DistributionStatus_Accouting)
      ) {
        maxRefundPricedd = util_Decimal_Subtract(Number(maxRefundPricedd), rebates.rebatesMoney);
      }
      if (body.refundPrice > Number(maxRefundPricedd)) {
        throw new Class_HttpException_Base('退款金额不能大于总金额减去已使用金额');
      }

      // 支付宝退款操作
      if (order.payType == Constant_Enum_Enum_Order_PayType.Order_PayType_ZfbPay) {
        const result = await this.alipay_Service.alipay_Refund({
          out_trade_no: order.orderNumber,
          refund_amount: body.refundPrice,
        });
        if (result != 'success') throw new Class_HttpException_Base(result);
      }

      // 更新商品
      const orderdd = await this.order_Repository
        .createQueryBuilder('order')
        .leftJoinAndSelect('order.orderVirtualDetail', 'orderVirtualDetail')
        .leftJoinAndSelect('orderVirtualDetail.good', 'good')
        .leftJoinAndSelect('orderVirtualDetail.seat', 'seat')
        .andWhere(`order.id = :id`, { id: body.orderId })
        .getOne();
      await manage.update(Good, orderdd.orderVirtualDetail.good, {
        seatsNum: orderdd.orderVirtualDetail.good.seatsNum - 1,
      });

      // 更新座位
      await manage.delete(Seat, orderdd.orderVirtualDetail.seat.id);

      // 更新订单
      await manage.update(Order, order.id, {
        status: Constant_Enum_Enum_Order_PayStatus.order_PayStatus_Refund,
        refundRemark: body.refundRemark,
      });

      // 更新分销订单状态
      if (rebates) {
        await manage.update(Rebates, Number(rebates.id), {
          rebatesStatus:
            Constant_Enum_Enum_Rebates_DistributionStatus.InviteRelation_DistributionStatus_Refund,
        });
      }

      await manage.delete(Seat, order.id);
      return '退款成功';
    });
  }

  async orderWeb_PayCallBack(body: Alipay_PayCallBack_SeClass) {
    return await this.entityManager.transaction(async (manage) => {
      // 判断是否支付成功
      // let orderData: { orderId: number; payPlatformTradeNo: string };
      // body.trade_no 则代表是支付宝
      // if (body.trade_no) {
      const result = this.alipay_Service.alipay_PayCallBack(body);
      const orderData = {
        orderId: Number(body.passback_params),
        payPlatformTradeNo: body.trade_no,
      };
      if (result != 'success') return;

      // 更新订单
      await manage.update(Order, Number(orderData.orderId), {
        payPlatformTradeNo: orderData.payPlatformTradeNo,
        status: Constant_Enum_Enum_Order_PayStatus.order_PayStatus_Pay,
      });

      // 更新座位
      const orderdd = await this.order_Repository
        .createQueryBuilder('order')
        .leftJoinAndSelect('order.orderVirtualDetail', 'orderVirtualDetail')
        .leftJoinAndSelect('orderVirtualDetail.good', 'good')
        .leftJoinAndSelect('orderVirtualDetail.seat', 'seat')
        .andWhere(`order.id = :id`, { id: orderData.orderId })
        .getOne();
      orderdd.orderVirtualDetail.seat.seatBuyTime = new Date().getTime();
      orderdd.orderVirtualDetail.seat.invalidTime =
        new Date().getTime() + orderdd.orderVirtualDetail.seat.good.product.productTime * 60 * 60 * 1000;
      await manage.save(Seat, orderdd.orderVirtualDetail.seat);

      // 更新优惠券
      const orderddd = await this.order_Repository
        .createQueryBuilder('order')
        .andWhere(`order.id = :id`, { id: orderData.orderId })
        .getOne();
      const couponUserClient = await this.couponUserClient_Repository
        .createQueryBuilder('couponUserClient')
        .leftJoinAndSelect('order.userClient', 'userClient')
        .where(`couponUserClient.coupon = :coupon`, { coupon: orderData.orderId })
        .andWhere(`couponUserClient.userClient = :userClient`, { userClient: orderddd.userClient.id })
        .getOne();
      couponUserClient.status = Constant_Enum_Enum_CouponUserClient_Status.ExCode_ExCodeValue_Used;
      await manage.update(CouponUserClient, couponUserClient.id, couponUserClient);

      // 更新分销订单状态
      const rebates = await this.rebates_Repository
        .createQueryBuilder('rebates')
        .where(`rebates.orderId= :orderId`, { orderId: orderData.orderId })
        .getOne();
      await manage.update(Rebates, Number(rebates.id), {
        rebatesStatus:
          Constant_Enum_Enum_Rebates_DistributionStatus.InviteRelation_DistributionStatus_OutGoing,
      });

      // 取消定时器
      const timeouts = this.schedulerRegistry.getTimeouts();
      if (
        timeouts.includes(
          `${orderData.orderId}-${Constant_Enum_Enum_Scheduled_Type.Scheduled_Type_OrderPay}`,
        )
      ) {
        this.schedulerRegistry.deleteTimeout(
          `${orderData.orderId}-${Constant_Enum_Enum_Scheduled_Type.Scheduled_Type_OrderPay}`,
        );
        const schedule = await this.scheduled_Service.scheduled_FindOneByName(
          `${orderData.orderId}-${Constant_Enum_Enum_Scheduled_Type.Scheduled_Type_OrderPay}`,
        );
        await manage.update(Scheduled, schedule.id, {
          status: Constant_Enum_Enum_Scheduled_Status.SCHEDULED_STATUS_DONE,
          scheduledd_at: new Date().getTime(),
        });
      }
      return 'success';
    });
  }
}
